package me.shurufa.fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.activities.SelectDigestBookActivity;
import me.shurufa.bean.ExcerptBook;
import me.shurufa.model.UserBookDigest;
import me.shurufa.model.UserBookDigestListResponse;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.RequestServerTask;
import me.shurufa.model.AddDigestBean;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.ExcerptBookResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.Utils;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 内容简介 Fragment
 */
public class DigestAddNoteFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.btn_select_digestbook)
    TextView mSelectDigestBookBtn;

    @Bind(R.id.et_page_num)
    EditText et_page_num;

    @Bind(R.id.et_note)
    EditText et_note;

    @Bind(R.id.tv_note_hint)
    TextView tv_note_hint;

    @Bind(R.id.et_digest)
    EditText et_digest;

    @Bind(R.id.iv_digest)
    ImageView iv_digest;

    @Bind(R.id.cb_save_not_send)
    CheckBox cb_save_not_send;

    @Bind(R.id.tv_save_send)
    TextView tv_save_send;

    private AddDigestBean mAddDigestBean;
    private String mAbsolutePath;
    private Handler mHandler = new Handler();

    public static DigestAddNoteFragment newInstance(String absolutePath, AddDigestBean addDigestBean) {
        DigestAddNoteFragment fragment = new DigestAddNoteFragment();
        Bundle args = new Bundle();
        args.putString(Constants.EXTRA_CAMERA_PHOTO, absolutePath);
        args.putSerializable(Constants.ARG_ADD_DIGEST, addDigestBean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mAddDigestBean = (AddDigestBean) getArguments().getSerializable(Constants.ARG_ADD_DIGEST);
            mAbsolutePath = getArguments().getString(Constants.EXTRA_CAMERA_PHOTO);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_digest_add_note, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        et_note.setOnFocusChangeListener(null);
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        initData();
        initListener();
    }

    private void initListener() {
        mSelectDigestBookBtn.setOnClickListener(this);
        tv_save_send.setOnClickListener(this);
        tv_note_hint.setOnClickListener(this);
        et_note.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (v != null && !hasFocus) {
                    if (TextUtils.isEmpty(et_note.getText())) {
                        tv_note_hint.setVisibility(View.VISIBLE);
                        et_note.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    private void initData() {
        if (mAddDigestBean.type == Constants.DIGEST_TYPE_TEXT) {
            iv_digest.setVisibility(View.GONE);
            et_digest.setVisibility(View.VISIBLE);
            et_digest.setText(mAddDigestBean.content);
        } else if (mAddDigestBean.type == Constants.DIGEST_TYPE_IMAGE) {
            // 显示图片书摘
            Bitmap bmp = BitmapFactory.decodeFile(mAbsolutePath);
            et_digest.setVisibility(View.GONE);
            iv_digest.setVisibility(View.VISIBLE);
            iv_digest.setImageBitmap(bmp);
        }

        // 若上一次选择过目录
        /*if (mAddDigestBean.menuId != 0L) {
            mSelectDigestBookBtn.setText(mAddDigestBean.chapterName);
        } else {
            loadDigestBookList();
        }*/

        //loadDigestBookList();
        getNewestExcerptBook();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                onNext();
                break;
            case R.id.btn_select_digestbook:
                Intent in = new Intent(getActivity(), SelectDigestBookActivity.class);
                SelectDigestBookActivity.initArguments(in, mAddDigestBean);
                startActivity(in);
                break;
            case R.id.tv_save_send:
                cb_save_not_send.toggle();
                break;
            case R.id.tv_note_hint:
                tv_note_hint.setVisibility(View.GONE);
                et_note.setVisibility(View.VISIBLE);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        et_note.requestFocus();
                        Utils.showSoftkeyboard(getActivity(), et_note);
                    }
                }, 50);

                break;
        }
    }

    // 右上角点击下一步
    private void onNext() {

    }

    /**
     * 选择书摘本
     * @param intent
     */
    public void onEventMainThread(Intent intent) {
        if (intent.getAction().equals(Constants.EVENT_SELECT_DIGEST_BOOK)){
            mAddDigestBean = (AddDigestBean) intent.getSerializableExtra(Constants.EVENT_SELECT_DIGEST_BOOK);
            mSelectDigestBookBtn.setText(mAddDigestBean.excerptedBookTitle);
        }
    }

    public AddDigestBean getAddDigestBean() {
        mAddDigestBean.content = et_digest.getText().toString();
        mAddDigestBean.pageNumber = et_page_num.getText().toString();
        mAddDigestBean.note = et_note.getText().toString();
        mAddDigestBean.publishState = cb_save_not_send.isChecked() ? Constants.SAVE : Constants.PUBLISH;
        return mAddDigestBean;
    }

    private void getNewestExcerptBook() {
        RequestParams params = new RequestParams();
        if (mAddDigestBean.bookId != 0) {
            params.addFormDataPart("book_id", mAddDigestBean.bookId);
        }
        HttpRequest.post(API.GET_EXCERPT_BOOK_NEWEST, params, new HttpCallback<ExcerptBookResp>() {

            @Override
            public void onRespSuccess(ExcerptBookResp resp) {
                try {
                    if (resp.data == null) {
                        return;
                    }
                    ExcerptBook excerptBook = resp.data;
                    mAddDigestBean.excerptedBookTitle = excerptBook.title;
                    mAddDigestBean.excerptedBookId = excerptBook.id;
                    mAddDigestBean.chapterBookId = String.valueOf(excerptBook.book_id);
                    mAddDigestBean.bookId = excerptBook.book_id;
                    mSelectDigestBookBtn.setText(mAddDigestBean.excerptedBookTitle);

                    if (TextUtils.isEmpty(mAddDigestBean.excerptedBookTitle)) {
                        mSelectDigestBookBtn.setText(getString(R.string.select_digest_book));
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(ExcerptBookResp resp) {

            }
        });
    }

    /**
     * 加载书摘本列表
     */
    private void loadDigestBookList() {
        new RequestServerTask<UserBookDigestListResponse>(UserBookDigestListResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();

                if (Global.currentUser != null && 0 != Global.currentUser.id) {
                    params.put("userId", Global.currentUser.id);
                }
                params.put("pageFrom", "");
                params.put("pageSize",Constants.PAGE_REQUEST_COUNT);
                params.put("pageDirection", Constants.DESC);
                return HttpUtil.post(API.GET_DIGEST_BOOKS, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(UserBookDigestListResponse result) {
                if (result.data == null || result.data.length == 0) {
                } else {
                    try {
                        UserBookDigest userBookDigest = result.data[0];
                        mAddDigestBean.excerptedBookTitle = userBookDigest.title;
                        mAddDigestBean.excerptedBookId = userBookDigest.id;
                        mAddDigestBean.chapterBookId = userBookDigest.getBook_id();
                        mAddDigestBean.bookId = Long.parseLong(userBookDigest.getBook_id());
                        mSelectDigestBookBtn.setText(mAddDigestBean.excerptedBookTitle);
                    } catch (Exception e) {
                    }
                }
            }
        }.start();
    }

}
